package gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @Author viento
 * @Date 2018/10/31 20:40
 * @Description TokenExistFilter 判断head是否存在Authorization
 * @Link 3576993219
 */
public class TokenExistFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        String requestUrl=RequestContext.getCurrentContext().getRequest().getServletPath();
        if (requestUrl.contains("/parking-orders/index")||requestUrl.contains("/parking-orders/wx")||requestUrl.contains("/parking-inspection/assistant/pay")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String author = request.getHeader("Authorization");
        String queryString=request.getQueryString();
        if (queryString!=null&&queryString.contains("token")) {
            try {
                author = URLDecoder.decode(queryString.substring(queryString.indexOf("Bearer"), queryString.length()),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isEmpty(author)){
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(200);
            context.getResponse().setContentType("application/json;charset=UTF-8");
            context.setResponseBody(JSON.toJSONString(""));
        }else {
            context.set("Authorization",author);
        }

        return null;
    }


}
